package com.tanhua.manage.controller;


import com.tanhua.common.pojo.Admin;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.AdminThreadLocal;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.manage.service.ManageUserService;
import com.tanhua.common.utils.MD5Util;
import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.manage.vo.ManageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;


@RestController
@RequestMapping("system/users")
@Slf4j
public class ManageUserController {

    @Autowired
    private ManageUserService manageUserService;

    /**
     * 管理员登录功能
     *
     * @return
     */
    @NoAuthorization
    @PostMapping("login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> map) {

        try {
            String username = map.get("username");
            String password = MD5Util.md5(map.get("password"));
            String verificationCode = map.get("verificationCode");
            String uuid = map.get("uuid");

            Map<String, Object> result = manageUserService.login(username, password, verificationCode, uuid);

            if (null != result) {
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.valueOf("密码或者验证码错误")).build();
    }
    /**
     * 获取验证码
     *
     * @return
     */
    @NoAuthorization
    @GetMapping("verification")
    public void verification(@RequestParam("uuid") String uuid, HttpServletResponse response) {

        BufferedImage vf = manageUserService.getVf(uuid);

        try {
            ImageIO.write(vf, "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @PostMapping("logout")
    public ResponseEntity<Void> logOut() {

        Boolean flag = this.manageUserService.logOut();

        return ResponseEntity.ok(null);
    }


    @NoAuthorization
    @PostMapping("profile")
    public ResponseEntity<ManageVo> profile() {
        try {
            ManageVo manageVo = this.manageUserService.profile();
            return ResponseEntity.ok(manageVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}
